<script setup lang="ts" xmlns:el-col="http://www.w3.org/1999/html">
import { uploadImageApi } from "@/api/file";
import { ArticleDraft, ArticleMdFrom, RandomImgFrom } from "@/api/article/type";
import { getCategoryOptionsApi } from "@/api/category";
import { getTagOptions } from "@/api/tag";
import {
  editVoByIdApi,
  pushApi,
  randomImgApi,
  saveOrUpdateArticleApi,
} from "@/api/article";
import { useRoute } from "vue-router";

const route = useRoute();

const mdEditorRef = ref();

// 表单信息
const formData = ref(<ArticleMdFrom>{
  id: null,
  title: "",
  summary: "",
  cover: "",
  content: "",
  categoryId: null,
  isDraft: true,
  tags: [],
  isPush: false,
  isTop: false,
  isOriginal: false,
  reproductionUrl: "",
});
// 草稿
const draft = ref(<ArticleDraft>{
  id: null,
  title: "",
  summary: "",
  text: "",
});

const pushArticleFromRef = ref(ElForm);

const pushArticlePopoverVisable = ref(false);

const categoryList = ref(<SelectBox[]>[]);
const tagsList: Ref<SelectBox[]> = ref(<SelectBox[]>[]);

const imgGetDialogVisible = ref(false);

const randomImgForm = ref(<RandomImgFrom>{});

const randomImgTypes = ref(<SelectBox[]>[
  {
    label: "妹子",
    value: "meizi",
  },
  {
    label: "动漫",
    value: "dongman",
  },
  {
    label: "风景",
    value: "fengjing",
  },
  {
    label: "随机",
    value: "suiji",
  },
]);

const randomImgUrl = ref("");

const formRules = computed(() => {
  return {
    title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
    summary: [{ required: true, message: "请输入简介", trigger: "blur" }],
    categoryId: [{ required: true, message: "分类不能为空", trigger: "blur" }],
    tags: [{ required: true, message: "标签不能为空", trigger: "blur" }],
    isTop: [{ required: true, message: "顶置不能为空", trigger: "blur" }],
    // isPush: [{required: true, message: '发布不能为空', trigger: 'blur'}],
    isOriginal: [{ required: true, message: "类型不能为空", trigger: "blur" }],
  };
});

/**
 * 保存文章信息
 */
const saveArticle = () => {
  saveOrUpdateArticleApi(formData.value).then(({ data: res }) => {
    formData.value.id = res.data;
  });
};

/**
 * 绑定@imgAdd event
 * @param pos 图片指针
 * @param $file 文件
 */
const imgAdd = (pos: any, $file: any) => {
  // 第一步.将图片上传到服务器.
  const data = new FormData();
  data.append("file", $file);
  // uploadImage 上传图片
  uploadImageApi(data).then(({ data: res }) => {
    ElMessage.success(res.data.msg);

    mdEditorRef.value.$img2Url(
      pos,
      import.meta.env.VITE_APP_BASE_API_FILE + res.data
    );
  });
};

/**
 * 随机图片获取，暂未对接
 */
const randomImgDialogOpen = () => {
  imgGetDialogVisible.value = true;
};

/**
 * 获取随机图片
 */
const getRandomImg = () => {
  randomImgApi(randomImgForm.value).then(({ data: res }) => {
    randomImgUrl.value = res.data;
  });
};

/**
 * 选择随机图片
 */
const selectRandomImg = () => {
  formData.value.cover = randomImgUrl.value;
  imgGetDialogVisible.value = false;
};

/**
 * 上传行为
 * @param data
 */
const uploadSectionFile = (data: any): any => {
  //TODO 覆盖默认的上传行为
};

/**
 * 发布动作 -> 打开最后的信息确认框
 */
const submitForm = async () => {
  pushArticleFromRef.value.validate(async (valid: boolean) => {
    if (valid) {
      await pushApi(formData.value).then(({ data: response }) => {
        if (response.code === 200) {
          formData.value.isDraft = false;
          pushArticlePopoverVisable.value = false;
          window.open(
            `${import.meta.env.VITE_APP_BLOG_WEB_API}/article/${formData.value.id}`,
            "_blank"
          );
        }
      });
      //
      pushArticlePopoverVisable.value = false;
    }
  });
};

/**
 * 分类修改
 */
const handleChangeCategory = () => {};

/**
 * 标签修改
 */
const handleChangeTags = () => {};

/**
 * 图片删除操作
 */
const imgDel = () => {};

/**
 * 打开文件上传框
 */
const triggerFileInput = () => {
  const upload: any = document.getElementById("upload");
  upload.click();
};

/**
 * 导入md
 * @param data
 */
const importMd = (data: any) => {
  // 获取文件
  const file = data.target.files[0];
  const fileName = file.name;
  if (!fileName.endsWith(".md")) {
    return ElMessage.warning({
      message: "文件类型不符合格式",
    });
  }
  // 设置文章标题 - 从文件名中取
  formData.value.title = fileName.substring(0, fileName.indexOf(".md"));

  // 文件读取
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = (res) => {
    console.log(res);
    if (res && res.target) {
      if (typeof res.target.result === "string") {
        formData.value.content = res.target.result;
      }
    }
  };
  ElMessage.success({
    message: "导入成功!若文章包含本地图片，需要手动导入",
  });
};

/**
 * 获取分类列表
 */
const getCategoryList = () => {
  // 获取分类列表
  getCategoryOptionsApi().then(({ data: res }) => {
    categoryList.value = res.data;
  });
};

/**
 * 获取标签列表
 */
const getTagList = () => {
  getTagOptions().then(({ data: res }) => {
    tagsList.value = res.data;
  });
};

/**
 * 获取文章信息
 */
const getArticle = () => {
  const { articleId } = route.query;
  if (articleId) {
    // 获取文章信息
    editVoByIdApi(articleId).then(({ data: res }) => {
      formData.value = res.data;
    });
  }
};

onMounted(() => {
  getCategoryList();
  getTagList();
  getArticle();
});
</script>

<template>
  <div class="app-container">
    <!--  头部  -->
    <el-card>
      <template #header>
        <div class="clearfix">
          <el-row>
            <el-col :span="12">
              <el-input
                v-model="formData.title"
                class="title"
                placeholder="请输入标题"
              />
            </el-col>
            <el-col :span="12" align="right">
              <el-button
                v-if="formData.isDraft"
                type="success"
                @click="saveArticle"
                >保存草稿</el-button
              >
              <el-popover
                :visible="pushArticlePopoverVisable"
                placement="left-start"
                title="发布文章"
                :width="500"
                trigger="click"
              >
                <el-form
                  ref="pushArticleFromRef"
                  :model="formData"
                  :rules="formRules"
                  label-width="80px"
                >
                  <el-form-item label="封面">
                    <template #label>
                      <div>
                        封面
                        <el-tooltip placement="bottom" effect="light">
                          <template #content>
                            <div style="text-align: right; margin: 0">
                              随机获取一张图片
                              <el-button
                                type="text"
                                size="small"
                                @click="randomImgDialogOpen()"
                              >
                                确定
                              </el-button>
                            </div>
                          </template>
                          <i-ep-QuestionFilled class="inline-block" />
                        </el-tooltip>
                      </div>
                    </template>

                    <el-upload
                      drag
                      class="upload-demo"
                      action="#"
                      :show-file-list="false"
                      :http-request="uploadSectionFile"
                    >
                      <el-image
                        v-if="formData.cover"
                        fit="cover"
                        :src="formData.cover"
                      />
                      <el-icon v-else class="el-icon--upload">
                        <upload-filled />
                      </el-icon>
                      <div class="el-upload__text">
                        将图片拖到此处，或<em>点击上传</em>
                      </div>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="分类" prop="categoryId">
                    <el-select
                      v-model="formData.categoryId"
                      placeholder="分类"
                      clearable
                      filterable
                      allow-create
                      default-first-option
                      @change="handleChangeCategory"
                      @clear="formData.categoryId = null"
                    >
                      <el-option
                        v-for="tags in categoryList"
                        :key="tags.value"
                        :label="tags.label"
                        :value="tags.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="标签" prop="tags">
                    <el-select
                      v-model="formData.tags"
                      :multiple-limit="3"
                      placeholder="标签"
                      clearable
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      @change="handleChangeTags"
                      @clear="formData.tags = []"
                    >
                      <el-option
                        v-for="tag in tagsList"
                        :key="tag.value"
                        :label="tag.label"
                        :value="tag.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="顶置" prop="isTop">
                    <el-radio-group v-model="formData.isTop">
                      <el-radio :value="true" size="large" border> 是</el-radio>
                      <el-radio :value="false" size="large" border>否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="类型" prop="isOriginal">
                    <el-radio-group v-model="formData.isOriginal">
                      <el-radio :value="true" size="large" border>
                        原创
                      </el-radio>
                      <el-radio :value="false" size="large" border>
                        转载
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item
                    v-if="!formData.isOriginal"
                    label="转载地址"
                    prop="originalUrl"
                  >
                    <el-input
                      v-model="formData.reproductionUrl"
                      placeholder="请输入转载地址"
                    />
                  </el-form-item>
                  <el-form-item label="简介" prop="summary">
                    <el-input
                      v-model="formData.summary"
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 4 }"
                      maxlength="250"
                      show-word-limit
                      style="width: 100%"
                      placeholder="请输入简介"
                    />
                  </el-form-item>
                </el-form>
                <div style="text-align: right; margin: 0">
                  <el-button @click="pushArticlePopoverVisable = false">
                    取消
                  </el-button>
                  <el-button type="primary" @click="submitForm()">
                    发 布
                  </el-button>
                </div>
                <template #reference>
                  <el-button
                    type="primary"
                    @click="pushArticlePopoverVisable = true"
                  >
                    发布
                  </el-button>
                </template>
              </el-popover>
            </el-col>
          </el-row>
        </div>
      </template>
      <div style="height: calc((100vh - 200px) - 1rem)">
        <mavon-editor
          ref="mdEditorRef"
          v-model="formData.content"
          style="height: 100%; width: 100%"
          codeStyle="idea"
          @img-add="imgAdd"
          @img-del="imgDel"
        >
          <template #left-toolbar-after>
            <button
              type="button"
              class="op-icon fa el-icon-document-add"
              aria-hidden="true"
              title="导入md文档"
              @click="triggerFileInput"
            >
              <i-ep-upload-filled />
            </button>
            <input
              v-show="false"
              id="upload"
              type="file"
              accept=".md"
              @change="importMd($event)"
            />
          </template>
        </mavon-editor>
      </div>
    </el-card>
    <!--  随机图片获取  -->
    <el-dialog v-model="imgGetDialogVisible" title="随机图片获取" width="500">
      <template #default>
        <el-form
          :model="randomImgForm"
          label-width="auto"
          style="max-width: 600px"
        >
          <el-form-item label="类型">
            <el-select
              v-model="randomImgForm.imgType"
              placeholder="请选择图片类型，不选就随机"
              clearable
            >
              <el-option
                v-for="option in randomImgTypes"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <el-image v-if="randomImgUrl" :src="randomImgUrl" fit="cover" />
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="getRandomImg" type="success" lazy>
            <span v-if="!randomImgUrl"> 获取 </span>
            <span v-else> 换一张 </span>
          </el-button>
          <el-button type="primary" @click="selectRandomImg">
            就选这张
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.title {
  font-size: 20px;
  width: 60%;

  :deep(.el-input__wrapper) {
    box-shadow: none;
  }
}

.upload-demo {
  width: 100%;
}
</style>
